<?php

/*

	This component is used to retrieve a list of suggested sports,
	according to the following algorithm:
	
	INPUT
		gender
		age
		weight
		height
		state
		interests
	OUTPUT
		ranked list of sports
	ALGORITHM
		imc = weight/(height*height)
		IF imc < 16
			imc_idx <- 2
		ELSE IF imc < 17
			imc_idx <- 4
		ELSE IF imc < 18.5
			imc_idx <- 8
		ELSE IF imc < 25
			imc_idx <- 16
		ELSE IF imc < 30
			imc_idx <- 32
		ELSE IF imc < 35
			imc_idx <- 64
		ELSE IF imc < 40
			imc_idx <- 128
		ELSE
			imc_idx <- 256

		# FILTER CANDIDATES

		candidates <- {}
		FOR_EACH sport IN sports
			IF sport.gender == A OR sport.gender == gender AND
			   sport.min_age <= age <= sport.max_age AND
			   sport.imc & imc_idx <> 0 AND
			   state >= sport.state AND
			   interest & sport.interests <> 0
				candidates <- candidates U {sport}
		END_FOR_EACH
		
		# RANK LIST OF CANDIDATES

		imc ---> more_restrictive_imc (1-num1s/8) (less 1s in sport.imc)
		age ---> farest to the maximum age (1-(age-min_age)/(max_age-min_age))
		state ---> more_restrictive_state ((state-1)/4)(less 1s in sport.state)

		score <- (imc+age+state)/3
*/


class SportRecommender extends CApplicationComponent 
{
	private $_config = array();
	
	//
	// Retrieves the sorted list of sports
	// up: user profile with all user's characteristics
	// ntop: number of sports to be returned
	public function getSports($up, $ntop)
	{
		$imc = $up->weight/($up->height*$up->height);
		if ($imc < 16)
			$imc_idx = 2;
		elseif ($imc < 17)
			$imc_idx = 4;
		elseif ($imc < 18.5)
			$imc_idx = 8;
		elseif ($imc < 25)
			$imc_idx = 16;
		elseif ($imc < 30)
			$imc_idx = 32;
		elseif ($imc < 35)
			$imc_idx = 64;
		elseif ($imc < 40)
			$imc_idx = 128;
		else
			$imc_idx = 256;
			
		# Filter candidates
		$sports=Sport::model()->find(array(
			'select'=>'id,name,type,imc,age,state',
			'condition'=>'
				(gender=A OR gender=:gender) AND 
				(min_age <= :age AND max_age >= :age) AND
				imc & :imc <> 0 AND
				state > :state AND
				interest & :interest <> 0
			',
			'params'=>array(
				':gender'=>$up->gender,
				':imc'=>$imc_idx,
				':age'=>$up->age,
				':state'=>$up->state,
				':interest'=>$up->interest,
			),
		));
		
		return $sports;
	}
}
